package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shiminghui
 * @date 2024/8/1 12:30
 * @description: TODO
 */
@Service
@RequiredArgsConstructor
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    private final CourseCategoryMapper courseCategoryMapper;


    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> list = courseCategoryMapper.selectTreeNodes(id);

        Map<String, CourseCategoryTreeDto> map = list.stream().filter(entity -> !id.equals(entity.getId())).collect(Collectors.toMap(entity -> entity.getId(), entity -> entity, (key1, key2) -> key2));
        //第一个参数是key,第二个参数是value,第三个参数是当key一样时,选择前面的,还是覆盖前面的


        //创建一个集合接收筛选后的对象
        ArrayList<CourseCategoryTreeDto> courseCategoryTreeDtos = new ArrayList<>();

        list.stream().filter(entity -> !id.equals(entity.getId())).forEach(entity -> {
            //收集
            if (entity.getParentid().equals(id)) {
                courseCategoryTreeDtos.add(entity);
            }
            //为收集的对象收集子节点

            CourseCategoryTreeDto categoryTreeDto = map.get(entity.getParentid());
            if (categoryTreeDto != null) {
                if (categoryTreeDto.getChildrenTreeNodes() == null) {
                    categoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                categoryTreeDto.getChildrenTreeNodes().add(entity);
            }
        });
        return courseCategoryTreeDtos;
    }

}
